package yanyan.com.tochar.funsactivity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.gs.buluo.common.widget.LoadingDialog;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;

import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import yanyan.com.tochar.FunsSketchActivity;
import yanyan.com.tochar.R;
import yanyan.com.tochar.adpter.FullyGridLayoutManager;
import yanyan.com.tochar.adpter.GridImageAdapter;
import yanyan.com.tochar.utils.CoreUtil;
import yanyan.com.tochar.utils.PictureSelectUtil;
import yanyan.com.tochar.utils.ToastUtil;

/**
 *  图片分割
 */
public class FunsSplitImageActivity extends Activity {
    private EditText hEd,zEd;

    private RecyclerView recyclerView;
    private GridImageAdapter adapter;
    private Bitmap oldBitmap;
    private ImageView resImg;
    private List imgList= new ArrayList<>();//图片集合
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_funs_spilt_img);
        recyclerView=findViewById(R.id.split_img_recycler);
        hEd=findViewById(R.id.split_img_hed);
        zEd=findViewById(R.id.split_img_zed);
        resImg=findViewById(R.id.split_img_resImg);

        //初始化图片选择
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(manager);
        adapter = new GridImageAdapter(this, new GridImageAdapter.onAddPicClickListener() {
            @Override
            public void onAddPicClick() {
                PictureSelectUtil.selectPohto(FunsSplitImageActivity.this,3306);
            }
        });
        adapter.setList(imgList);
        adapter.setSelectMax(1);
        recyclerView.setAdapter(adapter);
        //统计各功能
        CoreUtil.statisticalFuns(this,"funs_split_img");
    }

    /**
     * 选择图片事件
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==RESULT_OK){
            imgList = PictureSelector.obtainMultipleResult(data);
            adapter.setList(imgList);
            adapter.notifyDataSetChanged();
            LocalMedia localMedia= (LocalMedia) imgList.get(0);
            String path="";
            if(CoreUtil.isAndroidQ()){
                path=localMedia.getAndroidQToPath();
            }else {
                path= localMedia.getPath();
            }
            Bitmap oldBitmap = PictureSelectUtil.getBitmap(path);
            int h=Integer.parseInt(hEd.getText().toString()) ;
            int z=Integer.parseInt(zEd.getText().toString()) ;
            paintLine(oldBitmap, h, z);


        }
    }

    public void splitImage(View view){
        if(imgList!=null && imgList.size()>0){
            LoadingDialog.getInstance().show(FunsSplitImageActivity.this, "正在制作中...", false);//加载
            Observable.create(new ObservableOnSubscribe<String>() {
                @Override
                public void subscribe(ObservableEmitter<String> e) throws Exception {
                    try{
                        LocalMedia localMedia= (LocalMedia) imgList.get(0);
                        String path="";
                        if(CoreUtil.isAndroidQ()){
                            path=localMedia.getAndroidQToPath();
                        }else {
                            path= localMedia.getPath();
                        }
                        Bitmap bitmap = PictureSelectUtil.getBitmap(path);

                        int h=Integer.parseInt(hEd.getText().toString()) ;
                        int z=Integer.parseInt(zEd.getText().toString()) ;
                        splitImg(bitmap,h,z);
                        e.onComplete();
                    }catch (Exception e1){
                        e.onError(e1);
                    }
                }
            }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<String>() {
                @Override
                public void onSubscribe(Disposable d) {
                }
                @Override
                public void onNext(String s) {

                }
                @Override
                public void onError(Throwable e) {
                    LoadingDialog.getInstance().dismissDialog();
                    ToastUtil.showShotToast(FunsSplitImageActivity.this, "生成失败");
                }
                @Override
                public void onComplete() {
                    LoadingDialog.getInstance().dismissDialog();
                    ToastUtil.showShotToast(FunsSplitImageActivity.this, "生成成功,请到相册查看");
                }
            });

        }else {
            ToastUtil.showShotToast(this,"请选择图片");
        }

    }


    private void splitImg(Bitmap bitmap,int h,int z){
        List<Bitmap> bitmaps=new ArrayList<>();
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int xw=width/h;
        int yh=height/z;
            for (int y=0;y<z;y++){
                for (int x=0;x<h;x++){
                Bitmap res = Bitmap.createBitmap(bitmap, x * xw, y * yh,
                        xw, yh);
                PictureSelectUtil.savePhotoToSD(res,this);
            }
        }
    }

    private void paintLine(Bitmap bitmap,int x,int y){
        new Thread(new Runnable() {
            @Override
            public void run() {
                int width = bitmap.getWidth();
                int height = bitmap.getHeight();
                int propW=width/x;
                int propH=height/y;
                oldBitmap = bitmap.copy(Bitmap.Config.ARGB_8888,true);
                Canvas canvas=new Canvas(oldBitmap);
                //线的笔
                Paint paint = new Paint();
                paint.setColor(Color.WHITE);
                paint.setStrokeWidth(1);
                for(int i=0;i<x;i++){
                    canvas.drawLine(i*propW,0,i*propW,height,paint);
                }
                for(int i=0;i<y;i++){
                    canvas.drawLine(0,i*propH,width,i*propH,paint);
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        resImg.setImageBitmap(oldBitmap);
                    }
                });
            }
        }).start();
    }

}
